package com.xyhuo.leetcode.november;

import com.xyhuo.leetcode.common.ListNode;

/**
 * 两数相加
 * https://leetcode.cn/problems/add-two-numbers/
 *
 * @time 2023/11/21
 */
public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode t1 = l1, t2 = l2;
        ListNode lastNode = new ListNode();
        ListNode firstNode = lastNode;

        int add = 0;
        while (true) {
            int sum = add;
            if (t1 == null && t2 == null && sum == 0) {
                break;
            }
            if (null != t1) {
                sum += t1.val;
                t1 = t1.next;
            }
            if (null != t2) {
                sum += t2.val;
                t2 = t2.next;
            }

            int val;
            if (sum >= 10) {
                val = sum % 10;
                add = 1;
            } else {
                val = sum;
                add = 0;
            }
            ListNode tmp = new ListNode(val);
            lastNode.next = tmp;
            lastNode = tmp;


        }
        return firstNode.next;
    }
}
